package com.flyme.module.base.provider.listener;

import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.module.base.client.event.UserRegEvent;
import com.flyme.module.base.client.dto.SysUserDto;
import com.flyme.module.base.client.entity.SystemRole;
import com.flyme.module.base.provider.service.SysAccountService;
import com.flyme.module.base.provider.service.SysRoleService;
import com.flyme.module.base.provider.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class UserRegListener implements SmartApplicationListener {


    @Autowired
    private SysUserService userService;
    @Autowired
    private SysAccountService sysAccountService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 只有监听类型匹配才执行
     */
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventClass) {
        return eventClass == UserRegEvent.class;
    }


    @Override
    public boolean supportsSourceType(Class<?> aClass) {
        return true;
    }

    /**
     * 业务逻辑
     */
    @Override
    @Async
    public void onApplicationEvent(ApplicationEvent applicationEvent) {

        // 转换事件类型
        UserRegEvent userRegEvent = (UserRegEvent) applicationEvent;
        // 获取注册用户对象信息
        String userName = userRegEvent.getUserName();
        String mobile = userRegEvent.getMobile();
        String userType = userRegEvent.getUserType();
        String roleCode = userRegEvent.getRoleCode();
        Long companyId = userRegEvent.getCompanyId();
        String password = userRegEvent.getPassword();
        String compName = userRegEvent.getCompName();
        SysUserDto user = new SysUserDto();
        SystemRole nowRole = sysRoleService.findByRoleCode(roleCode);
        Long[] roles = {nowRole.getId()};
        user.setRoleIds(roles);
        user.setUserName(userName);
        user.setMobile(mobile);
        user.setPassword(CommonConstants.DEF_PWD);
        if(ObjectUtils.isNotEmpty(password)){
            user.setPassword(password);
        }
        user.setCompany(compName);
        user.setUserType(userType);
        user.setCompanyId(companyId);
        sysAccountService.register(user);
    }

    /**
     * 同步情况下监听执行的顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
